package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.*;
import com.leyou.search.pojo.Goods;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexService {
    @Autowired
    private ItemClient itemClient;
    public Goods buildGoods(SpuDTO spuDTO){
        //自动匹配id，brandId，subTitle
        Goods goods = BeanHelper.copyProperties(spuDTO, Goods.class);
        //skus 把id，title，image的第一张，price
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map =new HashMap<>();
        HashSet<Long> set = new HashSet<>();
        List<SkuDTO> skuDTOS = this.itemClient.querySkuById(spuDTO.getId());
        for (SkuDTO skuDTO : skuDTOS) {
            map.put("id",skuDTO.getId());
            map.put("title",skuDTO.getTitle());
            map.put("price",skuDTO.getPrice());
            map.put("image", StringUtils.substringBefore(skuDTO.getImages(),","));
            list.add(map);
            set.add(skuDTO.getPrice());
        }
       goods.setSkus(JsonUtils.toString(list));
        //all  所有需要被搜索的信息，包含标题，分类，甚至品牌

        List<CategoryDTO> categoryDTOList = this.itemClient.queryByIds(spuDTO.getCategoryIds());
        String s = categoryDTOList.stream().map(CategoryDTO::getName).collect(Collectors.joining(" "));
        Long id = spuDTO.getBrandId();
        BrandDTO brandDTO = this.itemClient.queryBrandById(id);
        String name = brandDTO.getName();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(spuDTO.getName()).append(s).append(name);
        goods.setAll(stringBuffer.toString());


        //categoryId
        goods.setCategoryId(spuDTO.getCid3());

        //createTime
        goods.setCreateTime(spuDTO.getCreateTime().getTime());

        //price
       goods.setPrice(set);


        //specs 可搜索的规格参数，key是参数名，值是参数值
        Map<String,Object> specs =new HashMap<>();
        List<SpecParamDTO> specParamDTOS = this.itemClient.querySpecParamByGid(null, spuDTO.getCid3(), true);
        SpuDetailDTO spuDetailDTO = this.itemClient.queryGoodsById(spuDTO.getId());
        Map<Long,Object> genericSpec = JsonUtils.nativeRead(spuDetailDTO.getGenericSpec(), new TypeReference<Map<Long, Object>>() {
        });
        Map<Long,List<String>> specialSpec =JsonUtils.nativeRead(spuDetailDTO.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });
        for (SpecParamDTO specParamDTO : specParamDTOS) {


            Long id1 = specParamDTO.getId();
            Object value =null;
            if (specParamDTO.getGeneric()){
                value=genericSpec.get(id1);
            }else {
                value=specialSpec.get(id1);
            }
            if (null==value||StringUtils.isBlank(value.toString())){
                value="其他";
            }
            // 判断是否是数值类型
            if(specParamDTO.getNumeric()){
                // 是数字类型，分段
                value = chooseSegment(value, specParamDTO);
            }

          specs.put(specParamDTO.getName(),value);

        }
        goods.setSpecs(specs);
        return goods;
    }
    private String chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

    private double parseDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return 0;
        }
    }
}
